/**
 * Created by tanbingqin on 2019/1/24.
 */
import React from 'react'
import menuRoute from 'routes/menuRoute'
import { connect } from 'react-redux'
import configureStore from "stores";
import { setRequestClose } from "actions/cache";
import { messages, deepFullCopy, dealCache, queryCurrencyPrecision } from "share/common";
import { Form, Tabs, Badge, Popover, Table, Affix, message, Input, Button } from 'antd'
import requestCloseService from 'containers/request-close/request-close.service'
import moment from 'moment'
import SearchArea from 'components/search-area'

class RequestClose extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      closeLoading: false,
      checkboxListForm: [{
        id: 'formOIDs',
        single: true,
        items: [
          {label: messages('approve.key87'/*单据名称*/), key: 'formOID', options: [{label: messages('request.key278'/*全部*/), value: 'all'}], checked: ['all']}
        ]
      }],
      searchForm: [
        {type: 'items', id: 'dateRange', items: [
          {type: 'date', id: 'startDate', label: messages('request.key291'/*起始日期*/)},
          {type: 'date', id: 'endDate', label: messages('request.key292'/*结束日期*/)}
        ]},
        {type: 'input', id: 'businessCodeKey', label: messages('approve.key63'/*单号*/)}
      ],
      columns: [
        {title: messages('common.sequence'/*序号*/), dataIndex: 'index', width: 80, render: (value, record, index) =>
          index + 1 + this.state.pageSize * this.state.page},
        {title: messages('request.key294'/*创建日期*/), dataIndex: 'createdDate', sorter: true, width: 120, render: (value, record) =>
          moment(value).format('YYYY-MM-DD')},
        {title: messages('request.key293'/*申请人*/), dataIndex: 'applicantName'},
        {title: messages('request.key290'/*单据名称*/), dataIndex: 'formName', render: value =>
          value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'},
        {title: messages('request.key295'/*事由*/), dataIndex: 'title', render: value => value ?
          <Popover placement="topLeft" content={value}>{value}</Popover> : '-'},
        {title: messages('request.key296'/*单号*/), dataIndex: 'businessCode'},
        {title: messages('request.key225'/*币种*/), dataIndex: 'originCurrencyCode', width: 48},
        {title: messages('approve.key74'/*金额*/), dataIndex: 'originCurrencyTotalAmount',align: 'right',
          render: (value, record)=>this.filterMoney(value, queryCurrencyPrecision(record.originCurrencyCode))},
        {title: messages('approve.key88'/*本币金额*/), dataIndex: 'totalAmount', align: 'right', sorter: true,
          render: (value, record)=>this.filterMoney(value, queryCurrencyPrecision(record.currencyCode))}
      ],
      sort: '',
      data: [],
      page: 0,
      pageSize: 10,
      pagination: {
        total: 0
      },
      searchParams: {},
      cacheSearchData: {}, //缓存筛选的数据
      selectedRowKeys: [], //选中的单据OID
      selectedRows: [], //选中的单据
      requestCloseDetail: menuRoute.getRouteItem('request-close-detail','key') //申请单关闭详情页
    }
  }

  componentDidMount(){
    this.getForms();
  }

  getForms = () => {
    let params = {
      companyOID: this.props.loginCompany.companyOID
    };
    let checkboxList = this.state.checkboxListForm;
    requestCloseService.getDocumentType(params).then(res => {
      let options = [{label: messages('request.key278'/*全部*/), value: 'all'}];
      Object.keys(res.data).map(key => {
        options.push({label: key, value: res.data[key].join(',')});
      });
      checkboxList.map(form => {
        if (form.id === 'formOIDs') {
          form.items.map(item => {
            item.key === 'formOID' && (item.options = options);
          })
        }
      });
      this.setState({
        checkboxListForm: checkboxList
      }, () => {
        this.getCache();
      })
    });
  };

  getList = () => {
    const { page, pageSize, searchParams, sort, cacheSearchData } = this.state;
    if (sort) {
      cacheSearchData.sort = sort;
      searchParams.sort = sort;
    }
    this.setState({ loading: true });
    requestCloseService.getRequestList(page, pageSize, searchParams).then(res => {
      this.setState({
        loading: false,
        data: res.data,
        pagination: {
          total: Number(res.headers['x-total-count']) || 0,
          current: page + 1,
          onChange: this.onChangePaper
        }
      })
    }).catch(() => {
      this.setState({ loading: false });
      message.error(messages('common.error1'));
    })
  };

  onChangePaper = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({ page: page - 1 }, () => {
        this.setCache(this.state.cacheSearchData);
      })
    }
  };

  //存储筛选数据缓存
  setCache = (result) =>{
    const { page } = this.state;
    result.page = page;
    this.setState({ cacheSearchData: result });
  };

  //获取筛选数据缓存
  getCache = () => {
    let result = this.props.requestClose;
    let { checkboxListForm, selectedRowKeys, selectedRows } = this.state;
    if (result && JSON.stringify(result) !== "{}") {
      checkboxListForm.map((item, index) => {
        checkboxListForm[index].items[0].checked = [result[item.id]] || [];
      });
      selectedRowKeys = result['selectedRowKeys'] || [];
      selectedRows = result['selectedRows'] || [];
      this.setState({ cacheSearchData: result, checkboxListForm, selectedRowKeys, selectedRows },() => {
        this.dealCache(result);
      })
    }
    else {
      let defaultSearchForm = deepFullCopy(this.state.searchForm);
      this.getList();
      this.setState({defaultSearchForm});
    }
  };

  //处理筛选缓存数据
  dealCache = (result) => {
    const { searchForm } = this.state;
    let defaultSearchForm = deepFullCopy(this.state.searchForm);
    if (result) {
      dealCache(searchForm, result);
      this.setState({
        page: result.page,
        defaultSearchForm
      }, () => {
        this.search(result);
        configureStore.store.dispatch(setRequestClose(null));
      })
    }
  };

  search = (values) => {
    this.setCache({...values});
    values.startDate && (values.startDate = moment(values.startDate).format('YYYY-MM-DD+00:00:00'));
    values.endDate && (values.endDate = moment(values.endDate).format('YYYY-MM-DD+23:59:59'));
    this.setState({
      searchParams: values,
      page: values.page ? values.page : 0,
      pagination: { total: 0 }
    },() => {
      this.getList();
    })
  };

  searchClear = () => {
    this.setState({ cacheSearchData: {} });
    this.setCache({});
    let {defaultSearchForm}=this.state;
    this.setState({
      searchParams: {},
      page: 0,
      searchForm: deepFullCopy(defaultSearchForm),
      pagination: { total: 0 }
    },() => {
      this.getList();
    })
  };

  handleTableChange = (pagination, filters, sorter) => {
    let page =  pagination.current;
    let sort = '';
    if(sorter.order){
      sort = `${sorter.columnKey},${sorter.order === 'ascend' ? 'ASC' : 'DESC'}`;
    }
    this.setState({
      page: page - 1,
      sort
    }, ()=>{
      this.getList();
    });
  };

  //列表选择更改
  onSelectChange = (selectedRowKeys) => {
    if (selectedRowKeys.length > 10) {
      message.warning(messages('request-close.key1')/*最多选择10条数据*/);
    } else {
      this.setState({ selectedRowKeys });
    }
  };

  //选择一行
  //选择逻辑：每一项设置selected属性，如果为true则为选中
  onSelectRow = (record, selected) => {
    let selectedRows = deepFullCopy(this.state.selectedRows);
    let item = JSON.stringify({
      applicationOID: record.applicationOID,
      entityType: 1001 //申请单
    });
    selected ? selectedRows.push(item) : selectedRows.delete(item);
    selectedRows.length <= 10 && this.setState({ selectedRows });
  };

  //全选
  onSelectAllRow = (selected) => {
    let selectedRows = deepFullCopy(this.state.selectedRows);
    this.state.data.map(item => {
      let row = JSON.stringify({
        applicationOID: item.applicationOID,
        entityType: 1001 //申请单
      });
      selected ? selectedRows.addIfNotExist(row) : selectedRows.delete(row);
    });
    selectedRows.length <= 10 && this.setState({ selectedRows });
  };

  close = () => {
    let params = {
      applicationOIDs: this.state.selectedRowKeys
    };
    this.setState({closeLoading: true});
    requestCloseService.handleClose(params).then(res => {
      if (res.status === 200) {
        message.success(messages('approve.key109',{arg1:res.data.successNum}/*成功处理 {arg1} 笔单据*/)+', '+
          messages('approve.key110',{arg1:res.data.failNum}/*失败 {arg1} 笔单据*/));
        this.setState({ closeLoading: false });
        this.setState({
          page: 0,
          pagination: { total: 0 },
          selectedRowKeys: [],
          selectedRows: [],
        },() => {
          this.getList();
        });
      }
    }).catch(e => {
      this.setState({ closeLoading: false });
      message.error(`${messages('common.operate.filed'/*操作失败*/)}，${e.response.data.message}`);
    });
  };

  handleRowClick = (record) => {
    let {cacheSearchData} = this.state;
    cacheSearchData.selectedRowKeys = this.state.selectedRowKeys;
    cacheSearchData.selectedRows = this.state.selectedRows;
    configureStore.store.dispatch(setRequestClose(cacheSearchData));
    let url = this.state.requestCloseDetail.url
      .replace(':formOID', record.formOID)
      .replace(':applicationOID', record.applicationOID)
      .replace(':pageFrom', 'closeList')
      .replace(':backType', 'history');
    this.context.router.push(url);
  };

  render() {
    const { loading, closeLoading, searchForm, checkboxListForm, columns, data, pagination, selectedRows, selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      onSelect: this.onSelectRow,
      onSelectAll: this.onSelectAllRow
    };
    return (
      <div>
        <SearchArea searchForm={searchForm}
                    checkboxListForm={checkboxListForm}
                    isReturnLabel
                    submitHandle={this.search}
                    clearHandle={this.searchClear}/>
        <div className="table-header">
          <div className="table-header-title">
            {messages('common.total', {total: pagination.total}/*共搜索到 {total} 条数据*/)}
            {` / ${messages('common.total.selected', {total: selectedRows.length})/*已选 {total} 条*/}`}
          </div>
          <div className="table-header-buttons">
            <Button type="primary" loading={closeLoading} disabled={!selectedRows.length} onClick={this.close}>{messages('request-close.key2')/*关闭*/}</Button>
          </div>
        </div>
        <Table rowKey="applicationOID"
               columns={columns}
               dataSource={data}
               pagination={pagination}
               rowSelection={rowSelection}
               onChange={this.handleTableChange}
               onRow={record => ({onClick: () => this.handleRowClick(record)})}
               loading={loading}
               bordered
               size="middle"/>
      </div>
    )
  }
}

RequestClose.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    requestClose: state.cache.requestClose,
    loginUser: state.login.loginUser,
    loginCompany: state.login.loginCompany
  }
}

export default connect(mapStateToProps)(RequestClose)
